"use client";
import React, { useState, useEffect, useCallback } from 'react';
import {
  Badge,
  Dropdown,
  List,
  Button,
  Empty,
  Avatar,
  Typography,
  Space,
  Tag,
  Tooltip,
  Switch,
  Modal,
  notification,
  App
} from 'antd';
import {
  BellOutlined,
  DeleteOutlined,
  CheckOutlined,
  NotificationOutlined,
  ClearOutlined,
  SettingOutlined
} from '@ant-design/icons';
import { getMyNoticeList, markNoticeRead, getUnreadNoticeCount } from '@/forent-api/api';
import { useListener } from '@/utils/sse/UseEventSource';
import moment from 'moment';

const { Text, Paragraph } = Typography;

// 通知类型映射
const noticeTypeMap: Record<string, { color: string; icon: React.ReactNode; bgColor: string }> = {
  info: { color: '#1890ff', icon: <NotificationOutlined />, bgColor: '#e6f7ff' },
  success: { color: '#52c41a', icon: <CheckOutlined />, bgColor: '#f6ffed' },
  warning: { color: '#faad14', icon: <BellOutlined />, bgColor: '#fffbe6' },
  error: { color: '#ff4d4f', icon: <DeleteOutlined />, bgColor: '#fff2f0' }
};

interface NotificationCenterProps {
  userId?: string; // 用户ID，用于SSE订阅
  displayMode?: 'popup' | 'click'; // 显示模式：弹出或点击
  enableBrowserNotification?: boolean; // 是否启用浏览器通知
  theme?: 'light' | 'dark'; // 主题
  showIcon?: boolean; // 是否显示图标
  iconClassName?: string; // 图标类名
  size?: number; // 图标大小
}

const NotificationCenter: React.FC<NotificationCenterProps> = ({ 
  userId,
  displayMode = 'popup',
  enableBrowserNotification = true,
  theme = 'light',
  showIcon = true,
  iconClassName = "",
  size = 40
}) => {
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [notifications, setNotifications] = useState<any[]>([]);
  const [unreadCount, setUnreadCount] = useState(0);
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [settingsVisible, setSettingsVisible] = useState(false);
  const [currentDisplayMode, setCurrentDisplayMode] = useState(displayMode);
  const [currentBrowserNotification, setCurrentBrowserNotification] = useState(enableBrowserNotification);
  const pageSize = 10;
  const { message } = App.useApp();

  // 主题样式
  const themeStyles = {
    light: {
      background: '#ffffff',
      border: '1px solid #e8e8e8',
      boxShadow: '0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 3px 6px -4px rgba(0, 0, 0, 0.12), 0 9px 28px 8px rgba(0, 0, 0, 0.05)',
      headerBg: '#fafafa',
      textColor: '#262626',
      subtextColor: '#8c8c8c'
    },
    dark: {
      background: '#1f1f1f',
      border: '1px solid #434343',
      boxShadow: '0 6px 16px 0 rgba(0, 0, 0, 0.3), 0 3px 6px -4px rgba(0, 0, 0, 0.2), 0 9px 28px 8px rgba(0, 0, 0, 0.2)',
      headerBg: '#262626',
      textColor: '#ffffff',
      subtextColor: '#bfbfbf'
    }
  };

  const currentTheme = themeStyles[theme];

  // 获取通知列表
  const fetchNotifications = useCallback(async (page = 1, prioritizeUnread = false) => {
    setLoading(true);
    try {
      let response;
      
      if (prioritizeUnread && page === 1) {
        // 优先获取未读消息（最近6条）
        const unreadResponse = await getMyNoticeList({
          current: 1,
          pageSize: 6,
          read_status: 0 // 只获取未读消息
        });
        
        if (unreadResponse.code === 200 && unreadResponse.data.list?.length > 0) {
          // 如果有未读消息，设置这些消息
          setNotifications(unreadResponse.data.list);
          setTotal(unreadResponse.data.total || 0);
          setCurrent(1);
          setLoading(false);
          return;
        }
        
        // 如果没有未读消息，继续获取所有消息
      }
      
      response = await getMyNoticeList({
        current: page,
        pageSize,
        read_status: undefined // 获取所有通知
      });
      
      if (response.code === 200) {
        if (page === 1) {
          setNotifications(response.data.list || []);
        } else {
          setNotifications(prev => [...prev, ...(response.data.list || [])]);
        }
        setTotal(response.data.total || 0);
        setCurrent(page);
      }
    } catch (error) {
      console.error('获取通知失败:', error);
    } finally {
      setLoading(false);
    }
  }, []);

  // 获取未读数量
  const fetchUnreadCount = useCallback(async () => {
    try {
      const response = await getUnreadNoticeCount();
      if (response.code === 200) {
        setUnreadCount(response.data.count || 0);
      }
    } catch (error) {
      console.error('获取未读数量失败:', error);
    }
  }, []);

  // 标记为已读
  const handleMarkRead = async (noticeId: number) => {
    try {
      const response = await markNoticeRead({ notice_id: noticeId });
      if (response.code === 200) {
        // 更新本地状态
        setNotifications(prev => 
          prev.map(item => 
            item.notice_id === noticeId 
              ? { ...item, read_status: 1, read_time: moment().format('YYYY-MM-DD HH:mm:ss') }
              : item
          )
        );
        // 更新未读数量
        fetchUnreadCount();
      }
    } catch (error) {
      console.error('标记已读失败:', error);
      message.error('标记已读失败');
    }
  };

  // 全部标记为已读
  const handleMarkAllRead = async () => {
    const unreadNotifications = notifications.filter(item => item.read_status === 0);
    
    if (unreadNotifications.length === 0) {
      message.info('没有未读消息');
      return;
    }
    
    try {
      await Promise.all(
        unreadNotifications.map(item => 
          markNoticeRead({ notice_id: item.notice_id })
        )
      );
      
      // 更新本地状态
      setNotifications(prev => 
        prev.map(item => ({ ...item, read_status: 1 }))
      );
      setUnreadCount(0);
      message.success('全部标记为已读');
    } catch (error) {
      console.error('批量标记已读失败:', error);
      message.error('批量标记已读失败');
    }
  };

  // 清除所有通知（重置列表）
  const handleClearAll = () => {
    Modal.confirm({
      title: '确认清除',
      content: '确定要清除所有通知吗？清除后将重新从服务器获取通知列表。',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        setNotifications([]);
        setCurrent(1);
        setTotal(0);
        fetchNotifications(1, false);
        message.success('通知列表已清除');
      }
    });
  };

  // 加载更多
  const handleLoadMore = () => {
    if (!loading && notifications.length < total) {
      fetchNotifications(current + 1, false); // 加载更多时不优先未读
    }
  };

  // SSE事件处理
  useEffect(() => {
    if (!userId) return;

    const cleanup = useListener(`user_${userId}`, (data) => {
      if (data.type === 'notice') {
        // 收到新通知，更新未读数量和列表
        fetchUnreadCount();
        if (visible) {
          fetchNotifications(1, true); // 重新获取第一页，优先未读
        }
        
        // 显示浏览器通知
        if (currentBrowserNotification && 'Notification' in window && Notification.permission === 'granted') {
          new Notification(data.data.title, {
            body: data.data.content,
            icon: '/favicon.ico',
            badge: '/favicon.ico',
            tag: 'notification-center'
          });
        }

        // 如果是弹出模式，使用notification弹出消息
        if (currentDisplayMode === 'popup') {
          const typeConfig = noticeTypeMap[data.data.notice_type] || noticeTypeMap.info;
          notification.open({
            message: data.data.title,
            description: data.data.content,
            icon: typeConfig.icon,
            placement: 'topRight',
            duration: 4.5,
            style: {
              backgroundColor: typeConfig.bgColor,
              borderLeft: `4px solid ${typeConfig.color}`
            },
            onClick: () => {
              // 点击通知时打开通知中心
              setVisible(true);
            }
          });
        }
      }
    });

    return cleanup;
  }, [userId, visible, fetchUnreadCount, fetchNotifications, currentBrowserNotification, currentDisplayMode]);

  // 初始化数据
  useEffect(() => {
    fetchUnreadCount();
  }, [fetchUnreadCount]);

  // 下拉菜单打开时获取通知列表
  const handleVisibleChange = (visible: boolean) => {
    setVisible(visible);
    if (visible) {
      fetchNotifications(1, true); // 优先获取未读消息
    }
  };

  // 请求浏览器通知权限
  useEffect(() => {
    if (currentBrowserNotification && 'Notification' in window && Notification.permission === 'default') {
      Notification.requestPermission();
    }
  }, [currentBrowserNotification]);

  // 设置面板
  const settingsPanel = (
    <div style={{ padding: '16px', width: 300 }}>
      <div style={{ marginBottom: 16 }}>
        <Text strong style={{ color: currentTheme.textColor }}>通知设置</Text>
      </div>
      <div style={{ marginBottom: 12 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Text style={{ color: currentTheme.textColor }}>显示模式</Text>
          <Switch
            checked={currentDisplayMode === 'popup'}
            onChange={(checked) => setCurrentDisplayMode(checked ? 'popup' : 'click')}
            checkedChildren="弹出"
            unCheckedChildren="点击"
          />
        </div>
        <Text type="secondary" style={{ fontSize: 12, color: currentTheme.subtextColor }}>
          弹出模式：收到新消息时自动弹出
        </Text>
      </div>
      <div style={{ marginBottom: 12 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Text style={{ color: currentTheme.textColor }}>浏览器通知</Text>
          <Switch
            checked={currentBrowserNotification}
            onChange={setCurrentBrowserNotification}
          />
        </div>
        <Text type="secondary" style={{ fontSize: 12, color: currentTheme.subtextColor }}>
          在浏览器中显示桌面通知
        </Text>
      </div>
    </div>
  );

  const notificationList = (
    <div 
      style={{ 
        width: 380, 
        maxHeight: 500, 
        background: currentTheme.background,
        border: currentTheme.border,
        borderRadius: 8,
        boxShadow: currentTheme.boxShadow,
        overflow: 'hidden'
      }}
    >
      {/* 头部 */}
      <div style={{ 
        padding: '16px 20px', 
        background: currentTheme.headerBg,
        borderBottom: `1px solid ${theme === 'light' ? '#f0f0f0' : '#434343'}`
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Text strong style={{ color: currentTheme.textColor, fontSize: 16 }}>
            通知消息
            {unreadCount > 0 && (
              <Badge 
                count={unreadCount} 
                style={{ marginLeft: 8 }}
                showZero={false}
              />
            )}
          </Text>
          <Space>
            <Tooltip title="设置">
              <Button 
                type="text" 
                size="small"
                icon={<SettingOutlined />}
                onClick={() => setSettingsVisible(true)}
                style={{ color: currentTheme.subtextColor }}
              />
            </Tooltip>
            {notifications.length > 0 && (
              <>
                <Tooltip title="全部已读">
                  <Button 
                    type="text" 
                    size="small"
                    icon={<CheckOutlined />}
                    onClick={handleMarkAllRead}
                    style={{ color: currentTheme.subtextColor }}
                  />
                </Tooltip>
                <Tooltip title="清除所有">
                  <Button 
                    type="text" 
                    size="small"
                    icon={<ClearOutlined />}
                    onClick={handleClearAll}
                    style={{ color: currentTheme.subtextColor }}
                  />
                </Tooltip>
              </>
            )}
          </Space>
        </div>
      </div>
      
      {/* 内容区域 */}
      <div style={{ maxHeight: 400, overflowY: 'auto' }}>
        {notifications.length === 0 ? (
          <div style={{ padding: 40, textAlign: 'center' }}>
            <Empty 
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description={
                <Text style={{ color: currentTheme.subtextColor }}>
                  暂无通知
                </Text>
              }
            />
          </div>
        ) : (
          <List
            itemLayout="horizontal"
            dataSource={notifications}
            loading={loading}
            renderItem={(item) => {
              const typeConfig = noticeTypeMap[item.notice.notice_type] || noticeTypeMap.info;
              const isUnread = item.read_status === 0;
              
              return (
                <List.Item
                  style={{
                    padding: '16px 20px',
                    backgroundColor: isUnread ? typeConfig.bgColor : 'transparent',
                    borderLeft: isUnread ? `4px solid ${typeConfig.color}` : '4px solid transparent',
                    cursor: 'pointer',
                    transition: 'all 0.3s ease',
                    borderBottom: `1px solid ${theme === 'light' ? '#f5f5f5' : '#2a2a2a'}`
                  }}
                  onClick={() => isUnread && handleMarkRead(item.notice_id)}
                >
                  <List.Item.Meta
                    avatar={
                      <Avatar 
                        size={40} 
                        style={{ 
                          backgroundColor: typeConfig.color,
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center'
                        }}
                        icon={typeConfig.icon}
                      />
                    }
                    title={
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <Text 
                          strong={isUnread}
                          style={{ 
                            fontSize: 14, 
                            color: currentTheme.textColor,
                            fontWeight: isUnread ? 600 : 400
                          }}
                          ellipsis={{ tooltip: item.notice.title }}
                        >
                          {item.notice.title}
                        </Text>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                          {item.notice.priority > 0 && (
                            <Tag 
                              color={item.notice.priority === 2 ? 'red' : 'orange'}
                              style={{ margin: 0, fontSize: 10 }}
                            >
                              {item.notice.priority === 2 ? '紧急' : '重要'}
                            </Tag>
                          )}
                          {isUnread && <Badge status="processing" />}
                        </div>
                      </div>
                    }
                    description={
                      <div>
                        <Paragraph 
                          ellipsis={{ rows: 2, tooltip: item.notice.content }}
                          style={{ 
                            margin: 0, 
                            fontSize: 13, 
                            color: currentTheme.subtextColor,
                            lineHeight: 1.4
                          }}
                        >
                          {item.notice.content}
                        </Paragraph>
                        <Text 
                          type="secondary" 
                          style={{ 
                            fontSize: 12, 
                            color: currentTheme.subtextColor,
                            marginTop: 4,
                            display: 'block'
                          }}
                        >
                          {moment(item.notice.create_time).fromNow()}
                        </Text>
                      </div>
                    }
                  />
                </List.Item>
              );
            }}
          />
        )}
      </div>
      
      {/* 底部 */}
      {notifications.length > 0 && notifications.length < total && (
        <div style={{ 
          padding: '12px 20px', 
          textAlign: 'center',
          borderTop: `1px solid ${theme === 'light' ? '#f0f0f0' : '#434343'}`,
          background: currentTheme.headerBg
        }}>
          <Button 
            type="link" 
            size="small"
            loading={loading}
            onClick={handleLoadMore}
            style={{ color: currentTheme.textColor }}
          >
            加载更多 ({notifications.length}/{total})
          </Button>
        </div>
      )}
    </div>
  );

  return (
    <>
      <Dropdown
        popupRender={() => notificationList}
        trigger={['click']}
        open={visible}
        onOpenChange={handleVisibleChange}
        placement="bottomRight"
        overlayStyle={{ padding: 0 }}
      >
        <Badge count={unreadCount} size="small" offset={[-2, 2]} style={{ width: 40, height: 40 }}>
        {showIcon && <Button
            type="text"
            icon={<BellOutlined className={iconClassName} style={{ fontSize: size }}/>}
            style={{ 
              border: 'none',
              boxShadow: 'none',
              color: unreadCount > 0 ? '#1890ff' : 'inherit',
              fontSize: 16,
              height: 40,
              width: 40,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              borderRadius: '50%',
              transition: 'all 0.3s ease'
            }}
          />}
        </Badge>
      </Dropdown>

      {/* 设置弹窗 */}
      <Modal
        title="通知设置"
        open={settingsVisible}
        onCancel={() => setSettingsVisible(false)}
        footer={null}
        width={350}
      >
        {settingsPanel}
      </Modal>
    </>
  );
};

export default NotificationCenter; 